package com.jeesit.cloud.spot.config.okhttp;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesit.cloud.exception.ServiceHandleException;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;

/**
 * @author syd
 * @description: feign 服务异常不进入熔断
 */
@Configuration
public class NotBreakerConfiguration {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }

    /**
     * 自定义错误
     */
    public class UserErrorDecoder implements ErrorDecoder {
        private Logger logger = LoggerFactory.getLogger(getClass());
        @Autowired
        private ObjectMapper objectMapper;

        @Override
        public Exception decode(String methosdKey, Response response) {
            ServiceHandleException serviceHandleException = null;
            try {
                Map<String, String> content = objectMapper.readValue(response.body().asInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                logger.error("feign 服务异常 ! content >>> {}", JSON.toJSONString(content));
                serviceHandleException = new ServiceHandleException("服务异常");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return serviceHandleException;
        }
    }
}
